package com.shigu.admin.common.actions;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shigu.admin.common.JSONResponse;
import com.shigu.admin.common.enums.PageType;
import com.shigu.admin.common.enums.ParamType;
import com.shigu.admin.common.freemarker.StringFreemarkerUtil;
import com.shigu.admin.common.service.CommonAdminService;
import com.shigu.admin.common.vo.OptionVO;
import com.shigu.admin.common.vo.PageInfoVO;
import com.shigu.admin.common.vo.ParamVO;
import com.shigu.admin.common.vo.SqlVO;
import com.shigu.exceptions.BaohuoException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公版后台
 * Created by zhaohongbo on 17/7/10.
 */
@Controller
public class CommonAdminAction {

    @Autowired
    private CommonAdminService commonAdminService;

    /**
     * 公版页面
     * @param request
     * @return
     */
    @RequestMapping("page")
    public String page(Long id,HttpServletRequest request, Model model) throws BaohuoException{
        Map<String,Object> data=new HashMap<>();
        data.putAll(commonAdminService.parseParamter(request.getParameterMap()));
        PageInfoVO pageInfo=commonAdminService.selPageById(id);
        if(pageInfo == null){
            throw new BaohuoException("页面不存在");
        }
        model.addAllAttributes(data);
        model.addAttribute("pageInfo",pageInfo);
        if (pageInfo.getType().equals(PageType.OUTER)) {
            return "redirect:"+pageInfo.getOuterUrl();
        }else if(pageInfo.getType().equals(PageType.USERDEFINE)){
            List<SqlVO> sqls=pageInfo.getSqlList();
            if (sqls != null) {
                for(int i=0;i<sqls.size();i++){
                    data.put("SQL"+i,commonAdminService.selDiyList(data,sqls.get(i).getSqlContent()));
                }
            }
            try {
                pageInfo.setHtml(StringFreemarkerUtil.parseString(data,pageInfo.getHtml()));
            } catch (Exception e) {
                throw new BaohuoException(e.getMessage());
            }
            if(pageInfo.getSqlList()!=null){
                for(int i=0;i<pageInfo.getSqlList().size();i++){
                    SqlVO vo=pageInfo.getSqlList().get(i);
                    List<Map<String,Object>> result=commonAdminService.selDiyList(data,vo.getSqlContent());
                    model.addAttribute("SQL"+i,result);
                    data.put("SQL"+i,result);
                }
            }
            return "commonAdmin/page_userdefine";
        }else{//还要计算分页
            if(pageInfo.getSqlList()!=null){
                SqlVO sql=pageInfo.getSqlList().get(0);
                String sqlStr=sql.getSqlContent();
                String pageStr=request.getParameter("page");
                String rowStr=request.getParameter("row");
                Integer page=1;
                Integer row=15;
                if(StringUtils.isNotEmpty(pageStr)){
                    page=Integer.valueOf(pageStr);
                }
                if (StringUtils.isNotEmpty(rowStr)) {
                    row=Integer.valueOf(rowStr);
                }
                int start=(page-1)*row;
                List<Map<String,Object>> result = commonAdminService.selDiyList(data,sqlStr+" limit "+start+","+row);
                model.addAttribute("SQL0",result);
                data.put("SQL0",result);
                //计算总条数
                String countSql="select count(1) as totalcount "+sqlStr.substring(sqlStr.indexOf("from"),sqlStr.length());
                List<Map<String,Object>> count = commonAdminService.selDiyList(data,countSql);
                long total=(Long)(count.get(0).get("totalcount"));
                long allpages=total/row;
                if(total%row>0){
                    allpages++;
                }
                model.addAttribute("totalPages",allpages);
            }
            //参数放上默认值
            if (pageInfo.getParams() != null) {
                for(ParamVO pvo:pageInfo.getParams()){
                    String defaultValue= (String) data.get(pvo.getField());
                    if(defaultValue == null){
                        continue;
                    }
                    if(pvo.getPtype() == ParamType.INPUT){
                        pvo.setDefaultValue(defaultValue);
                    }else if(pvo.getPtype() == ParamType.SELECT){
                        List<OptionVO> optionVOs=pvo.getOptions();
                        if (optionVOs != null) {
                            for(OptionVO option:optionVOs){
                                if(option.getValue().equals(defaultValue)){
                                    option.setHasSelect(true);
                                }
                            }
                        }
                    }
                }
            }
        }
        return "commonAdmin/page_datacell";
    }

    /**
     * 公版本json
     * @return
     */
    @RequestMapping("jsondata")
    @ResponseBody
    public JSONObject json(Long id,HttpServletRequest request) throws BaohuoException {
        Map<String,Object> data=new HashMap<>();
        data.putAll(commonAdminService.parseParamter(request.getParameterMap()));
        SqlVO sqlVO=commonAdminService.selSqlVO(id);
        JSONResponse response=new JSONResponse();
        List<Map<String,Object>> result=commonAdminService.selDiyList(data,sqlVO.getSqlContent());
        if(result != null && result.size()>0){
            response.put("data",result);
        }
        return JSON.parseObject(JSON.toJSONString(response));
    }

    /**
     * json普通单对象查询
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("admindata/jsonObj")
    @ResponseBody
    public JSONObject jsonObj(Long id,HttpServletRequest request) throws BaohuoException {
        Map<String,Object> data=new HashMap<>();
        data.putAll(commonAdminService.parseParamter(request.getParameterMap()));
        SqlVO sqlVO=commonAdminService.selSqlVOByFunId(id);
        JSONResponse response=new JSONResponse();
        List<Map<String,Object>> result=commonAdminService.selDiyList(data,sqlVO.getSqlContent());
        if(result != null && result.size()>0){
            response.put("data",result.get(0));
        }
        return JSON.parseObject(JSON.toJSONString(response));
    }

    /**
     * json普通数组对象查询
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("admindata/jsonArr")
    @ResponseBody
    public JSONObject jsonArr(Long id,HttpServletRequest request) throws BaohuoException {
        Map<String,Object> data=new HashMap<>();
        data.putAll(commonAdminService.parseParamter(request.getParameterMap()));
        SqlVO sqlVO=commonAdminService.selSqlVOByFunId(id);
        JSONResponse response=new JSONResponse();
        List<Map<String,Object>> result=commonAdminService.selDiyList(data,sqlVO.getSqlContent());
        if(result != null && result.size()>0){
            response.put("data",result);
        }
        return JSON.parseObject(JSON.toJSONString(response));
    }

    /**
     * json含分页对象查询
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("admindata/jsonTable")
    @ResponseBody
    public JSONObject jsonTable(Long id,HttpServletRequest request) throws BaohuoException {
        Map<String,Object> data=new HashMap<>();
        data.putAll(commonAdminService.parseParamter(request.getParameterMap()));
        SqlVO sqlVO=commonAdminService.selSqlVOByFunId(id);
        JSONResponse response=new JSONResponse();
        List<Map<String,Object>> result=commonAdminService.selDiyList(data,sqlVO.getSqlContent());
        if(result != null && result.size()>0){
            response.put("data",result);
        }else{
            response.put("data",new ArrayList<>());
        }
        String sqlStr=sqlVO.getSqlContent();
        String countSql="select count(1) as totalcount "+sqlStr.substring(sqlStr.indexOf("from"),sqlStr.length());
        result=commonAdminService.selDiyList(data,countSql);
        if(result != null && result.size()>0){
            response.put("total",result.get(0).get("totalcount"));
        }else {
            response.put("total",0);
        }
        return JSON.parseObject(JSON.toJSONString(response));
    }


    @RequestMapping({"adminpage/*","adminpage/*/*","adminpage/*/*/*"})
    public String wapIndex() {
        return "adminIndex";
    }
}
